package com.chris.exception;

import com.chris.model.ResultCode;
import com.chris.model.ResultMsg;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * 自定义异常翻译器，针对用户名、密码错误，授权类型不对的异常进行处理
 */
public class OAuthServerWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity<ResultMsg> translate(Exception e) throws Exception {
        ResultMsg resultMsg = doTranslateHandler(e);
        return new ResponseEntity(resultMsg, HttpStatus.UNAUTHORIZED);
    }

    /**
     * 根据系统定制返回异常
     * @param e
     * @return
     */
    private ResultMsg doTranslateHandler(Exception e){
        //默认值，系统错误
        ResultCode resultCode = ResultCode.UNAUTHORIZED;
        if(e instanceof UnsupportedGrantTypeException){
            //判断异常，不支持的认证方式
            resultCode = ResultCode.UNSUPPORTED_GRANT_TYPE;
        }else if(e instanceof InvalidGrantException){
            //判断异常，用户名或密码错误
            resultCode = ResultCode.USERNAME_OR_PASSWORD_ERROR;
        }
        return new ResultMsg(resultCode.getCode(),resultCode.getMsg(),null);
    }
}
